from xml.sax import make_parser
from xml.sax.handler import ContentHandler 
import csv #So that it can do all the clever formating for a list of strings to be converted to a CVS row!!

#This will parse a http://www.parkenet.com/BibleXML/XMLBibleUserGuide.html formatted xml file for a bible into
# .cvs format, needed for GAE bulkuploading via app...

# It is aimed towards the models.Chapter model
# writer2 is for the model of the per-books data (generally fairly constant per translations)
class bible2cvs (ContentHandler):

  def __init__ (self):
    self.chapContents = "" # Shouldn't be needed :(

  def characters (self, ch): 
    self.chapContents += ch

  def startElement(self, name, attrs): 

   if name == 'bible': 
    self.bookno = 0;
    self.translation = attrs.get('translation',"")
    print "Converting sources/" + self.translation + ".xml to csv/" + self.translation + "chaps.xml"
    self.writer = csv.writer(open("csv/" + self.translation + "chaps.csv", "wb"))
    self.writer2 = csv.writer(open("csv/" + self.translation + "books.csv", "wb"))

   elif name == 'book': 
     self.bookname = attrs.get('name',"") 
     self.chapcount = 0
     self.bookno += 1;
     self.cvsbookrow = [self.translation, self.bookno, self.bookname]
     
   elif name == 'chapter':
     self.chapcount += 1;
     self.chapContents = ""
     self.versescount = 0
     self.cvsrow = [self.translation, self.bookno, self.chapcount]

   #We change an attribute to ("v"-tagged) content chars, since we will be printing verse numbers. Then v can just be a css style
   if name == 'verse': 
     self.chapContents += "<v>" + attrs.get('ref',"") + "</v>"
     self.versescount += 1

   return

  def endElement(self, name): 

   if name == 'chapter': 
     self.cvsrow.append(self.versescount)
     self.cvsrow.append(self.chapContents)
     #Now can write this row:
     self.writer.writerow(self.cvsrow)

   elif name == 'book': 
     self.cvsbookrow.append(self.chapcount)
     self.writer2.writerow(self.cvsbookrow)

   elif name == 'bible': 
     print "Done!"


chapparser = make_parser(  )
handler = bible2cvs(  )
chapparser.setContentHandler(handler)


